package com.easydata.agent.core.dataIO;

import com.easydata.agent.config.TaskConfiguration;
import com.easydata.agent.core.DAGContext;
import com.easydata.agent.exceptions.TaskException;
import com.easydata.libPlugin.core.IDataReader;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;

public class FileCacheDataReader implements IDataReader {
    private DAGContext context;
    private String id;
    FileInputStream fis;

    public FileCacheDataReader(DAGContext context, String id) {
        this.context = context;
        this.id = id;
    }

    @Override
    public void open() throws Exception {

        String path = TaskConfiguration.getInstance().getCacheDir() + "/" + this.context.getTaskId() + "/";
        var file = new File(path);

        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new TaskException(-1, "can not create the cache dir");
            }
        }

        fis = new FileInputStream(path + this.id + ".bin");
    }

    @Override
    public byte[] read() throws Exception {
        byte[] bytes = fis.readNBytes(4);
        int len = ByteBuffer.wrap(bytes).getInt();
        return fis.readNBytes(len);
    }

    @Override
    public int size() throws Exception {
        throw new TaskException(-1, "not supported");
    }

    @Override
    public void close() throws Exception {
        fis.close();
    }
}
